package org.edu.modules.growth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.base.controller.BaseController;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.growth.entity.VeJsczWorkCount;
import org.edu.modules.growth.service.IVeJsczWorkCountService;
import org.edu.modules.growth.vo.QueryCondition;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Api(tags="工作量管理")
@RestController
@RequestMapping("jsczWorkCount")
@Slf4j
@AllArgsConstructor
public class VeJsczWorkCountController extends BaseController<VeJsczWorkCount, IVeJsczWorkCountService> {

    private IVeJsczWorkCountService mIVeJsczWorkCountService;


    @ApiOperation(value = "分页查询")
    @PostMapping("/selectPage")
    public Result<?> selectPage(@RequestBody QueryCondition queryCondition ) {
        return Result.OK(mIVeJsczWorkCountService.selectPage(queryCondition));
    }

    /**
     * 根据id详情
     */
    @ApiOperation(value = "根据id详情")
    @PostMapping("/getDetail")
    public Result<VeJsczWorkCount> getDetail(@RequestParam("id") Long id) {
        return Result.OK(mIVeJsczWorkCountService.getById(id));
    }

    /**
     * 保存与编辑
     */
    @ApiOperation(value = "保存与编辑信息")
    @PostMapping("/addOrUpdate")
    public Result<?> addOrUpdate(@RequestBody VeJsczWorkCount jsczWorkCount) {
        if( jsczWorkCount.getId() != null ){
            Map<String,Object> map = mIVeJsczWorkCountService.editById(jsczWorkCount) ;
            if( (Boolean)map.get("result") ){
                return Result.OK();
            }
            return Result.error(map.get("msg").toString());
        }
        // 查询对应工号老师、学期是否有数据
        QueryWrapper<VeJsczWorkCount> wrapper = new QueryWrapper<>() ;
        wrapper.eq("GH",jsczWorkCount.getGH()) ;
        wrapper.eq("semId",jsczWorkCount.getSemId()) ;
        List<VeJsczWorkCount> list =  mIVeJsczWorkCountService.list(wrapper) ;
        // 若存在同学期工作量，数据覆盖
        if( !CollectionUtils.isEmpty(list) ){
            jsczWorkCount.setId(list.get(0).getId()) ;
            return Result.OK(mIVeJsczWorkCountService.updateById(jsczWorkCount));
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Long time = System.currentTimeMillis()/1000;
        jsczWorkCount.setAddTime(time).setTerminalId(1L)
                .setAddUserId(Long.parseLong(user.getId()));
        return Result.OK(mIVeJsczWorkCountService.save(jsczWorkCount));
    }


    /**
     * 删除
     */
    @ApiOperation(value = "删除")
    @PostMapping("/removeById")
    public Result<?> removeById(@RequestParam("id") Long id) {
        return Result.OK(mIVeJsczWorkCountService.removeById(id));
    }

    /**
     * 批量删除
     */
    @ApiOperation(value = "批量删除")
    @PostMapping("/removeByIds")
    public Result<?> removeByIds(@RequestBody List<Long> ids) {
        if( !CollectionUtils.isEmpty(ids) ){
            return Result.OK(mIVeJsczWorkCountService.removeByIds(ids));
        }
        return Result.error( "传输参数为空！" );
    }

    /**
     * 导出
     */
    @AutoLog(value = "工作量导出excel表格")
    @ApiOperation(value = "工作量导出excel表格")
    @PostMapping(value = "export")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "XM", value = "姓名-模糊", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "GH", value = "工号", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "semId", value = "学期Id", dataType = "Long")
    })
    public ModelAndView excelExport(@RequestParam(value = "XM",required = false) String XM,
                                    @RequestParam(value = "GH",required = false) String GH,
                                    @RequestParam(value = "semId",required = false) String semId) {
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //查询
        QueryWrapper<VeJsczWorkCount> wrapper = new QueryWrapper<>() ;
        if( XM != null ){
            wrapper.like("XM",XM) ;
        }
        if( GH != null ){
            wrapper.eq("GH",GH) ;
        }
        if( semId != null ){
            wrapper.eq("semId",semId) ;
        }
        wrapper.orderByDesc("id");
        List<VeJsczWorkCount> list = mIVeJsczWorkCountService.list(wrapper) ;
        mv.addObject(NormalExcelConstants.FILE_NAME, "工作量信息");
        mv.addObject(NormalExcelConstants.CLASS, VeJsczWorkCount.class);
//        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();user.getRealname()
        ExportParams exportParams = new ExportParams("工作量信息", "导出人:", "工作量信息");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }

    /**
     * 导入
     */
    @AutoLog(value = "工作量导入excel表格")
    @ApiOperation(value = "工作量导入excel表格")
    @PostMapping(value = "import")
    public Result<?> excelImport(MultipartFile file) {
        ImportParams params = new ImportParams();
        params.setTitleRows(2);
        params.setHeadRows(1);
        params.setNeedSave(true);
        try {
            List<VeJsczWorkCount> list = ExcelImportUtil.importExcel(file.getInputStream(), VeJsczWorkCount.class, params);
            mIVeJsczWorkCountService.excelImport(list);
            return Result.OK("文件导入成功！数据行数：" + list.size());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("文件导入失败:" + e.getMessage());
        } finally {
            try {
                file.getInputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
